#!/usr/bin/python3

import json
import requests
import datetime
from pathlib import Path

my_gitee_config = ".gitee.json"

class gitee_config():
    def __init__(self):
        self.config = str(Path.home()) + "/" + my_gitee_config
        self.json = None
        with open(self.config, 'r') as fp:
            self.json = json.load(fp)

    def get(self, k):
        if self.json:
            if k in self.json:
                return self.json[k]
            else:
                print("no such key: {:}".format(k))
        else:
            print("cannot init from {:}".format(self.config))
        return ""

    def set(self, k, v):
        if self.json:
            self.json[k] = v;

    def save(self):
        with open(self.config, 'w') as fp:
            json.dump(self.json, fp, ensure_ascii=False, indent=4, separators=(',', ':'))


def get_access_token(email, passwd, clientid, clientsecret):
    url="https://gitee.com/oauth/token"
    headers = { 'Content-Type': 'application/json',
            'charset' : 'UTF-8' }
    params = {
            "grant_type":"password",
            "username" : email,
            "password" : passwd,
            "client_id" : clientid,
            "client_secret" : clientsecret,
            "scope" : "user_info projects pull_requests issues notes keys hook groups gists enterprises"
            }
    r = requests.post(url = url, headers = headers, params = params)
    data = r.json()
    if "access_token" in data:
        return (data["access_token"], data["expires_in"])
    else:
        return ("", 0)

def update_token(cfg):
    email = cfg.get("useremail")
    passwd = cfg.get("userpasswd")
    clientid = cfg.get("clientid")
    clientsecret = cfg.get("clientsecret")
    if len(email) == 0 or len(passwd) == 0 or len(clientid) == 0 or len(clientsecret) == 0:
        return ""

    now = datetime.datetime.now()

    (token, expire) = get_access_token(email, passwd, clientid, clientsecret)
    if len(token) == 0:
        return token
    cfg.set("access_token", token);
    now += datetime.timedelta(seconds=expire - 60)
    timestr = now.strftime('%Y-%m-%d %H:%M:%S')
    cfg.set("access_token_expire", timestr)
    cfg.save()
    return token

def load_gitee_config_and_update_token():
    cfg = gitee_config()

    token = cfg.get('access_token')
    if len(token) == 0:
        update_token(cfg)

    now = datetime.datetime.now()
    expire_time_str = cfg.get("access_token_expire")
    if len(expire_time_str) == 0:
        update_token(cfg)

    expire = datetime.datetime.strptime(expire_time_str, '%Y-%m-%d %H:%M:%S')
    if now > expire:
        update_token(cfg)

    return cfg
